#include "stdafx.h"
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QDebug>

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_downloader(new HttpDownloader(this))
{
    ui->setupUi(this);

    // 设置窗口标题
    setWindowTitle("Qt HTTP文件下载器");

    // 初始化UI
    ui->progressBar->setRange(0, 100);
    ui->progressBar->setValue(0);

    // 设置默认URL
    ui->urlEdit->setText("https://cdn-lfs-cn-1.modelscope.cn/prod/lfs-objects/64/9e/136c731c1a1ab7f9af8b4a465404159f25c19d3affc2883cc2453e09c638?filename=model.onnx");
    ui->pathEdit->setText("model.onnx");

    // 连接信号槽
    connect(m_downloader, &HttpDownloader::progressChanged, this, &MainWindow::onProgressChanged);
    connect(m_downloader, &HttpDownloader::speedUpdated, this, &MainWindow::onSpeedUpdated);
    connect(m_downloader, &HttpDownloader::statusChanged, this, &MainWindow::onStatusChanged);
    connect(m_downloader, &HttpDownloader::finished, this, &MainWindow::onFinished);
    connect(m_downloader, &HttpDownloader::errorOccurred, this, &MainWindow::onErrorOccurred);

    // 连接按钮信号
    connect(ui->downloadBtn, &QPushButton::clicked, this, &MainWindow::onDownloadClicked);
    connect(ui->pauseBtn, &QPushButton::clicked, this, &MainWindow::onPauseClicked);
    connect(ui->resumeBtn, &QPushButton::clicked, this, &MainWindow::onResumeClicked);
    connect(ui->cancelBtn, &QPushButton::clicked, this, &MainWindow::onCancelClicked);
    connect(ui->browseBtn, &QPushButton::clicked, this, [this]() {
        QString filePath = QFileDialog::getSaveFileName(this, "选择保存位置", "download.file");
        if (!filePath.isEmpty()) {
            ui->pathEdit->setText(filePath);
        }
        });

    updateUI();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::onDownloadClicked()
{
    QString url = ui->urlEdit->text().trimmed();
    QString filePath = ui->pathEdit->text().trimmed();

    if (url.isEmpty()) {
        QMessageBox::warning(this, "错误", "请输入下载URL");
        return;
    }

    if (filePath.isEmpty()) {
        QMessageBox::warning(this, "错误", "请输入保存路径");
        return;
    }

    m_downloader->startDownload(url, filePath);
    updateUI();
}

void MainWindow::onPauseClicked()
{
    m_downloader->pauseDownload();
    updateUI();
}

void MainWindow::onResumeClicked()
{
    m_downloader->resumeDownload();
    updateUI();
}

void MainWindow::onCancelClicked()
{
    m_downloader->cancelDownload();
    updateUI();
}

void MainWindow::onProgressChanged(double percentage, qint64 bytesReceived, qint64 bytesTotal)
{
    ui->progressBar->setValue(static_cast<int>(percentage));

    QString progressText;
    if (bytesTotal > 0) {
        progressText = QString("%1% (%2/%3)")
            .arg(percentage, 0, 'f', 1)
            .arg(formatTimeRemaining(bytesTotal - bytesReceived, m_downloader->getSpeed().toDouble()))
            .arg(bytesTotal);
    }
    else {
        progressText = QString("下载中... (%1)").arg(bytesReceived);
    }

    ui->progressLabel->setText(progressText);
}

void MainWindow::onSpeedUpdated(const QString& speed)
{
    ui->speedLabel->setText("速度: " + speed);
}

void MainWindow::onStatusChanged(const QString& status)
{
    ui->statusLabel->setText("状态: " + status);
}

void MainWindow::onFinished(bool success, const QString& message)
{
    if (success) {
        QMessageBox::information(this, "成功", message);
    }
    else {
        QMessageBox::warning(this, "完成", message);
    }
    updateUI();
}

void MainWindow::onErrorOccurred(const QString& error)
{
    QMessageBox::critical(this, "错误", error);
    updateUI();
}

void MainWindow::updateUI()
{
    bool isDownloading = m_downloader->isDownloading();

    ui->downloadBtn->setEnabled(!isDownloading);
    ui->pauseBtn->setEnabled(isDownloading);
    ui->resumeBtn->setEnabled(!isDownloading && m_downloader->getDownloadedSize() > 0);
    ui->cancelBtn->setEnabled(isDownloading || m_downloader->getDownloadedSize() > 0);

    ui->urlEdit->setEnabled(!isDownloading);
    ui->pathEdit->setEnabled(!isDownloading);
    ui->browseBtn->setEnabled(!isDownloading);
}

QString MainWindow::formatTimeRemaining(qint64 bytesRemaining, double speed)
{
    if (speed <= 0) return "未知";

    double seconds = bytesRemaining / speed;
    int hours = static_cast<int>(seconds) / 3600;
    int minutes = (static_cast<int>(seconds) % 3600) / 60;
    int secs = static_cast<int>(seconds) % 60;

    if (hours > 0) {
        return QString("%1:%2:%3").arg(hours, 2, 10, QLatin1Char('0'))
            .arg(minutes, 2, 10, QLatin1Char('0'))
            .arg(secs, 2, 10, QLatin1Char('0'));
    }
    else {
        return QString("%1:%2").arg(minutes, 2, 10, QLatin1Char('0'))
            .arg(secs, 2, 10, QLatin1Char('0'));
    }
}